from django.shortcuts import render
from rest_framework.views import APIView, Response
from django.db import transaction
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from . import serializers
from django.forms import model_to_dict
import json
from interview import models


# Create your views here.

class ScoreView(APIView):
    '''
    分数
    '''

    def post(self, request):
        upload_data = request.data

        client_no = upload_data.get('client_no', '')
        score = upload_data.get('score', '')
        try:
            client_no = int(client_no)
            score = int(score)
        except Exception as e:
            # print(e)
            return Response(data=dict(rescode=1, msg="参数不合适", data=''))

        player = models.Player.objects.filter(id=client_no).first()
        # print(client_no)
        # print(score)
        # print(player)
        if not player:
            return Response(data=dict(rescode=1, msg="未找到该人", data=''))
        with transaction.atomic():
            models.Score.objects.create(
                player=player,
                score=score,
            )
            charts_one, created = models.Charts.objects.get_or_create(
                player=player,
            )
            charts_one.score = score
            charts_one.save()

        return Response(data=dict(rescode=0, msg="", data=''))


class ChartsView(APIView):
    '''
    排行榜
    '''

    def get(self, request):
        client_no = request.GET.get("client_no", "")
        start = request.GET.get("start", "")
        end = request.GET.get("end", "")
        try:
            client_no = int(client_no)
            start = int(start)
            end = int(end)

        except Exception as e:
            # print(e)
            return Response(data=dict(rescode=1, msg="参数不合适", data=''))

        # print(client_no)
        # print(score)
        # print(player)
        player = models.Player.objects.filter(id=client_no).first()
        if not player:
            return Response(data=dict(rescode=1, msg="未找到该人", data=''))

        # print(client_no, start, end)
        charts_list = models.Charts.objects.all().order_by("-score")[start:end:]
        # print(charts_list)
        charts_list = serializers.ChartsSerializer(charts_list, many=True).data
        # print(charts_list)

        self_charts = models.Charts.objects.filter(player=player).first()
        # print('self_charts', self_charts)
        # if self_charts:
        #     charts_list.append(serializers.ChartsSerializer(self_charts).data)
        ids = []
        for i in charts_list:
            ids.append(i.get('id'))

        # print(ids)
        ids_1 = [i for i in ids]
        ids_1.append(self_charts.player.id)
        players = models.Player.objects.filter(id__in=ids_1)
        players = serializers.PlayerSerializer(players, many=True).data
        players_map = {i.get('id'): i.get('name') for i in players}
        # print(players_map)
        data = []
        self_order_no = models.Charts.objects.filter(score__gt=self_charts.score).count() + 1
        print('self_order_no', self_order_no, self_charts.player.id)
        print('ids', ids, )
        order_map = {}
        for i in range(len(charts_list)):
            name = players_map.get(charts_list[i].get('id'))
            data.append({
                'order_no': start + i + 1,
                'name': name,
                'score': charts_list[i].get('score')
            })
            order_map[charts_list[i].get('id')] = {
                'order_no': start + i + 1,
                'name': name,
                'score': charts_list[i].get('score')
            }

        print('order_map', order_map)
        if self_charts:
            if self_charts.player.id in ids:
                data.append(order_map[self_charts.player.id])
            else:
                data.append({
                    'order_no': self_order_no,
                    'name': players_map.get(self_charts.player.id),
                    'score': self_charts.score
                })

        return Response(data=dict(rescode=0, msg="", data=json.dumps(data)))
